package org.zhaya.sdk.processors.condition;

import io.logz.sawmill.Condition;
import io.logz.sawmill.Doc;
import io.logz.sawmill.Template;
import io.logz.sawmill.TemplateService;
import io.logz.sawmill.annotations.ConditionProvider;
import io.logz.sawmill.parser.ConditionParser;
import io.logz.sawmill.utilities.JsonUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.inject.Inject;
import java.util.Map;

import static java.util.Objects.requireNonNull;

@ConditionProvider(type = "startWith", factory = StartWithCondition.Factory.class)
public class StartWithCondition implements Condition {

    private final String field;
    private final Object value;

    public StartWithCondition(String field, Object value) {
        this.field = field;
        this.value = value;
    }

    @Override
    public boolean evaluate(Doc doc) {
        if (!doc.hasField(field)) {
            return false;
        }

        Object fieldValue = doc.getField(field);
        if (fieldValue instanceof String) {
            return String.valueOf(fieldValue).startsWith(((Template) value).render(doc));
        } else {
            return false;
        }
    }

    public static class Factory implements Condition.Factory {
        private final TemplateService templateService;

        @Inject
        public Factory(TemplateService templateService) {
            this.templateService = requireNonNull(templateService);
        }

        @Override
        public Condition create(Map<String, Object> config, ConditionParser conditionParser) {
            Configuration startWithConfig = JsonUtils.fromJsonMap(Configuration.class, config);
            return new StartWithCondition(startWithConfig.getField(), templateService.createTemplate((String) startWithConfig.getValue()));
        }
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Configuration {
        private String field;
        private Object value;

    }
}